import { NavBar, InfiniteScroll, Toast } from 'antd-mobile'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/component/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import NoComment from './components/NoComment'
import { useNavigate, useParams } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { useEffect, useState } from 'react'
import {
  getArtCommentAction,
  getArticleByIdAction
} from '@/store/reducers/article'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai.css'
import { FollowingAction, unFollowingAction } from '@/store/reducers/profile'
import CommentInput from './components/CommentInput'
import CommentReply from './components/CommentReply'
import { Comment } from '@/api'
// 导入防止xss攻击
const DomPurify = require('dompurify')
const Article = () => {
  const navigate = useNavigate()
  // 获取路径参数
  const { id } = useParams()

  // 调用redux
  const dispatch = useAppDispatch()

  // 调用文章详情
  useEffect(() => {
    dispatch(getArticleByIdAction(id!))
    dispatch(getArtCommentAction(id!))
  }, [dispatch, id])

  // 获取文章详情数据
  const { articleInfo, commentRes } = useAppSelector(state => state.articler)

  // 设置高亮
  useEffect(() => {
    hljs.configure({
      ignoreUnescapedHTML: true
    })
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach(el => {
      hljs.highlightElement(el as HTMLElement)
    })
  }, [articleInfo])

  // 关注与取关
  const toggleFollow = () => {
    const { art_id, aut_id, is_followed } = articleInfo
    // 取消
    if (is_followed === true) {
      dispatch(unFollowingAction({ art_id, aut_id }))
    } else {
      // 关注
      dispatch(FollowingAction({ art_id, aut_id }))
    }
    Toast.show({
      icon: 'success',
      content: is_followed ? '取消成功' : '关注成功'
    })
  }

  // 控制评论弹窗
  const [inputShow, setInputShow] = useState(false)
  const [reShow,setReShow] = useState(false)
  const [source,setSource]=useState<Comment>({} as Comment)
  // 显示评论的评论弹窗
  const showReFn =async (com:Comment) =>{
   await setSource(com)
   await setReShow(true)
  }
  
  const renderArticle = () => {
    // 文章详情
    return (
      <div className='wrapper'>
        <div className='article-wrapper'>
          <div className='header'>
            <h1 className='title'>{articleInfo.title}</h1>

            <div className='info'>
              <span>{articleInfo.pubdate}</span>
              <span>{articleInfo.read_count} 阅读</span>
              <span>{articleInfo.comm_count} 评论</span>
            </div>

            <div className='author'>
              <img src='http://geek.itheima.net/images/user_head.jpg' alt='' />
              <span className='name'>{articleInfo.aut_name}</span>
              <span
                onClick={toggleFollow}
                className={classNames(
                  'follow',
                  articleInfo.is_followed ? 'followed' : ''
                )}
              >
                {articleInfo.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>
          <div className='content'>
            <div
              className='content-html dg-html'
              dangerouslySetInnerHTML={{
                __html: DomPurify.sanitize(articleInfo.content || '')
              }}
            />
            <div className='date'>发布文章时间：{articleInfo.pubdate}</div>
          </div>
        </div>

        <div className='comment'>
          <div className='comment-header'>
            <span>全部评论（{articleInfo.comm_count}）</span>
            <span>20 点赞</span>
          </div>

          <div className='comment-list'>
            {commentRes?.results?.length === 0 && <NoComment />}
            {commentRes?.results?.map(v => {
              return <CommentItem show={showReFn} com={v} key={v.com_id} />
            })}

            <InfiniteScroll
              hasMore={false}
              loadMore={async () => {
                console.log(1)
              }}
            />
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.root}>
      <div className='root-wrapper'>
        <NavBar
          onBack={() => navigate(-1)}
          right={
            <span>
              <Icon type='icongengduo' />
            </span>
          }
        >
          {true && (
            <div className='nav-author'>
              <img src={articleInfo.aut_photo} alt='' />
              <span className='name'>{articleInfo.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  articleInfo.is_followed ? 'followed' : ''
                )}
              >
                {articleInfo.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter
          articleInfo={articleInfo}
          show={() => setInputShow(true)}
        />
      </div>
      <CommentReply source={source} visible={reShow} close={()=>{
        setReShow(false)
        setSource({} as Comment)
      }} show={()=>setInputShow(true)}/>
      <CommentInput source={source} visible={inputShow} close={() => setInputShow(false)} articleInfo={articleInfo}/>
    </div>
  )
}

export default Article
